package com.fruit.service.task;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fruit.constants.TaskConstant;
import com.fruit.pojo.task.TaskLog;
import com.fruit.service.log.TaskLogManager;
import com.fruit.service.order.FruitTreeUnbindManager;
import com.fruit.util.CommonUtil;
import com.fruit.util.CustomUtil;
import com.fruit.util.DateUtil;
import com.fruit.util.ResultInfo;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service("fruitTaskJob")
public class FruitTaskJob {
	protected Logger logger = LoggerFactory.getLogger(FruitTaskJob.class);
	@Autowired
	private FruitTreeUnbindManager fruitTreeUnbindService;
	
	@Autowired
	private TaskLogManager taskLogService;
	
	public void updateFruitUnbindJob(){
		String tradeId = CommonUtil.getUUID();
		String curTime = DateUtil.getDay();
		log.info("[{}]-【解除果树绑定关系-任务调度】-【开始】",tradeId,curTime);
		TaskLog tl = null;
		try {
			tl = taskLogService.insertTaskLog(tradeId, "解除果树绑定关系-任务调度", DateUtil.getTime());
			if(tl != null){
			Map<String,Object> resMap = fruitTreeUnbindService.updateFruitUnbind(tradeId, curTime);
				ResultInfo result = (ResultInfo)resMap.get("result");
				if(ResultInfo.SUCCESS.equals(result.getState())){
					tl.setState(TaskConstant.LogState.success.getValue());
					log.info("[{}]-【解除果树绑定关系-任务调度】-【成功】",tradeId);
				}else{
					tl.setState(TaskConstant.LogState.fail.getValue());
					log.error("[{}]-【解除果树绑定关系-任务调度】-【失败】",tradeId);
				}
				tl.setEndTime(DateUtil.getTime());
				tl.setCode(result.getCode());
				tl.setMessage(result.getMessage());
			}
		} catch (Exception e) {
			log.error("[{}]-【解除果树绑定关系-任务调度】-【异常】----{}",tradeId,CustomUtil.getStackTraceAsString(e));
			if(tl != null){
				tl.setState(TaskConstant.LogState.fail.getValue());
				tl.setEndTime(DateUtil.getTime());
				tl.setCode("exception");
				tl.setMessage("解除果树绑定关系-任务调度-异常");
			}
		}finally {
			log.info("[{}]-【解除果树绑定关系-任务调度】-【结束】",tradeId);
			if(tl != null){
				taskLogService.updateTaskLog(tl);
			}
		}
		
	}
	
}
